var page = {
  init: function () {
    let that = this;
    // 点击重新监测
    // chrome.runtime.onMessage.addListener(function (
    //   message,
    //   sender,
    //   sendResponse
    // ) {
    //   if (message.message === "2") {
    //     console.log(message.message, "clickme 2");
    //     localStorage.removeItem(document.domain); //删除localStorage
    //     localStorage.setItem("hp", "2");
    //     that.monitorPopup();
    //   }
    // });
    window.addEventListener("load", () => {
      //监测多端登陆的域名
      if (this.moniterLoginDomain.indexOf(location.host) > -1) {
        console.log("检测重复1");
        this.monitorPopup();
      }
    });
  },
  moniterLoginDomain: [
    "mp.toutiao.com", //头条
    "weibo.com", //微博
    "mp.sohu.com", //搜狐
    "www.weibo.com", //微博
    "om.qq.com", //企鹅号
    "xueqiu.com", //雪球
    "www.zhihu.com", //知乎
    "mp.163.com", //网易号
    "mp.yidianzixun.com", //一点号
    "creator.douyin.com", //抖音
    "cp.kuaishou.com", // 快手
    "www.bilibili.com", // b站
    "creator.xiaohongshu.com", // 小红书
    "dtying.com", // 灯影
    "channels.weixin.qq.com", // 视频号
    "www.ximalaya.com", //喜马拉雅
    "admin.qingting.fm", //蜻蜓fm
    "t.10jqka.com.cn", // 同花顺
    "mp.dayu.com", // 大鱼号
    "baijiahao.baidu.com", // 百家号
    "mp.weixin.qq.com", // 微信公众号
    "mp.qutoutiao.net", // 趣头条
    "www.mafengwo.cn", // 马蜂窝
    "bbs.qyer.com", // 穷游
    "www.meipai.com", // 美拍
    "mp.iqiyi.com", // 爱奇艺
    "tv.sohu.com", // 搜狐视频
    "www.56.com", // 56视频
    "dream.haokan.com", // 好看视频
    "haokan.baidu.com", // 好看视频
    "studio.ixigua.com", // 西瓜视频
    "s.alipay.com", //支付宝企业版
    "sweb.alipay.com", //个人版
    "finshop.jd.com", //京东金融
    "f.gw.com.cn", //大智慧
    "sns.tdx.com.cn", //通达信
  ],

  monitorPopup: function () {
    setTimeout(() => {
      this.monitLoginRemove();
      if (localStorage.getItem(document.domain)) {
        localStorage.removeItem("hp");
        return false;
      }
      if (localStorage.getItem("hp") == 2) {
        this.initTzwMonitor();
      }
    }, 500);
  },
  processData(inputData) {
    let cookiesArray = [];

    // 分割输入数据为每个键值对
    let cookiePairs = inputData.split("; ");

    // 遍历每个键值对，生成对象并加入数组
    cookiePairs.forEach((pair) => {
      let [name, value] = pair.split("=");

      // 去除可能存在的空格
      name = name.trim();
      value = value.trim();

      let cookieObject = JSON.stringify({
        domain: document.domain,
        expires: 1715566125.042,
        httpOnly: true,
        name: name,
        path: "/",
        sameSite: "NONE",
        secure: false,
        value: value,
      });

      cookiesArray.push(cookieObject);
    });

    return cookiesArray;
  },
  //轮询监听登录
  async initTzwMonitor() {
    console.log("444");
    const monitorHandle = window.setInterval(() => {
      console.log("轮询");
      this.monitLogin(async (nameCn, nameEn) => {
        console.log("登录了");
        clearInterval(monitorHandle);
        let tempObj = {};
        if (nameEn === "xueqiu") {
          const elements = document.getElementsByClassName("user__col--lf");
          for (const element of elements) {
            const firstLink = element.querySelector("a:first-child");
            if (firstLink) {
              tempObj["xueqiu_user_id"] = firstLink.href.replace(/\D/g, "");
            }
          }
          const nameElement = document.querySelector(".user__col--name");
          if (nameElement) {
            tempObj["nickName"] = nameElement?.innerHTML;
          }
          const avatarImg = document.querySelector(
            '.user__col--lf a[class="avatar"] img'
          );
          if (avatarImg) {
            tempObj["xueqiu_account_avatar"] = avatarImg.src;
          }
          tempObj["cookies"] = this.processData(document.cookie);
          tempObj["doMain"] = document.domain;
        }

        if (nameEn == "tonghuashun") {
          tempObj["cookies"] = this.processData(document.cookie);
          tempObj["doMain"] = document.domain;
        }

        chrome.runtime.sendMessage(
          { action: "getCookies1", tempObj: tempObj },
          function (response) {
            console.log(localStorage.getItem("hp"), ".......................");
            if (localStorage.getItem("hp") == 2) {
              // 创建 loading 元素
              var loadingOverlay = document.createElement("div");
              loadingOverlay.style.position = "fixed";
              loadingOverlay.style.top = "0";
              loadingOverlay.style.left = "0";
              loadingOverlay.style.width = "100%";
              loadingOverlay.style.height = "100%";
              loadingOverlay.style.backgroundColor = "rgba(255, 255, 255, 0.8)"; // 半透明白色背景
              loadingOverlay.style.zIndex = "9999"; // 确保 loading 元素在最顶层
              var loadingText = document.createElement("div");
              loadingText.style.position = "absolute";
              loadingText.style.top = "50%";
              loadingText.style.left = "50%";
              loadingText.style.transform = "translate(-50%, -50%)";
              loadingText.style.fontSize = "24px";
              loadingText.style.color = "#333";
              loadingText.textContent = "检测到您已登录，可以关闭了";
              loadingOverlay.appendChild(loadingText);
              document.body.appendChild(loadingOverlay);
              localStorage.removeItem("hp");
            }
          }
        );
        // if (localStorage.getItem("hp") == 2) {
        //   chrome.runtime.sendMessage(
        //     { action: "getCookies", tempObj: tempObj },
        //     function (response) {

        //     }
        //   );
        // }
      });
    }, 1000);
  },
  //监听登录
  async monitLoginRemove(callback) {
    // 发现雪球登陆了, 检测头像;
    if (location.host == "xueqiu.com") {
      if (!document.getElementById("side_user_name")) {
        localStorage.removeItem(document.domain); //删除localStorage
      }
    }
    // 发现同花顺登陆了, 检测头像;
    if (location.host == "t.10jqka.com.cn") {
      // 查找具有 id 为 'header_logined' 的 DOM 元素
      var headerLogined = document.getElementById("header_logined");
      if (headerLogined) {
        // 获取元素的 display 样式
        var displayStyle = window
          .getComputedStyle(headerLogined)
          .getPropertyValue("display");
        // 判断 display 样式是否为 'block'
        if (displayStyle === "block") {
          // callback("同花顺", "tonghuashun");
        } else {
          localStorage.removeItem(document.domain); //删除localStorage
        }
      } else {
        console.log("未找到具有 id 为 'header_logined' 的 DOM 元素");
      }
    }
    //发现头条登陆了,检测头像
    if (location.host == "mp.toutiao.com") {
    }
  },

  //监听登录
  async monitLogin(callback) {
    //发现雪球登陆了,检测头像
    if (location.host == "xueqiu.com") {
      if (document.getElementById("side_user_name")) {
        localStorage.setItem(document.domain, true);

        callback("雪球", "xueqiu");
      }
    }
    //发现同花顺登陆了,检测头像
    if (location.host == "t.10jqka.com.cn") {
      // 查找具有 id 为 'header_logined' 的 DOM 元素
      var headerLogined = document.getElementById("header_logined");
      if (headerLogined) {
        // 获取元素的 display 样式
        var displayStyle = window
          .getComputedStyle(headerLogined)
          .getPropertyValue("display");
        // 判断 display 样式是否为 'block'
        if (displayStyle === "block") {
          callback("同花顺", "tonghuashun");
        } else {
          console.log("元素的 display 样式不是 'block'");
        }
      } else {
        console.log("未找到具有 id 为 'header_logined' 的 DOM 元素");
      }
    }
    //发现头条登陆了,检测头像
    if (location.host == "mp.toutiao.com") {
      callback("头条", "toutiao");
    }
  },
};
page.init();
// 轮询检查本地存储中是否存在 localCookie 字段
function waitForElements(selector) {
  return new Promise((resolve, reject) => {
    let interval = setInterval(() => {
      const elements = document.querySelectorAll(selector);
      if (elements.length > 0) {
        clearInterval(interval);
        resolve(Array.from(elements));
      }
    }, 100);
  });
}

function monitoring() {
  console.log("------1111");
  if (window.location.href.includes("distribution/platform")) {
    const checkLocalCookie = setInterval(() => {
      let cookieVal = JSON.parse(localStorage.getItem("localCookie"));
      let dataType = localStorage.getItem("dataType");
      if (dataType) {
        // 如果 localCookie 字段存在
        console.log("localCookie 字段存在，执行操作...");
        // 在这里执行你想要的操作

        // 停止轮询
        clearInterval(checkLocalCookie);
        if (dataType === "xueqiu.com") {
          setTimeout(() => {
            chrome.runtime.sendMessage(
              { action: "setCookie", cookieVal },
              function (response) {}
            );
          }, 1000);
          localStorage.removeItem("dataType");
          localStorage.removeItem("localCookie");
          window.open("https://xueqiu.com", "_blank");
        } else {
          // 创建一个消息提示框
          const messageDiv = document.createElement("div");
          messageDiv.textContent = "暂未开放登录";
          messageDiv.style.backgroundColor = "#E6A23C";
          messageDiv.style.color = "#fff";
          messageDiv.style.position = "fixed";
          messageDiv.style.top = "10px";
          messageDiv.style.left = "50%";
          messageDiv.style.transform = "translateX(-50%)";
          messageDiv.style.padding = "10px";
          messageDiv.style.borderRadius = "5px";
          messageDiv.style.zIndex = "9999";

          // 将消息提示框添加到页面中
          document.body.appendChild(messageDiv);

          // 一定时间后自动隐藏消息提示框
          setTimeout(() => {
            messageDiv.style.display = "none";
          }, 2000); // 3秒后隐藏消息提示框
        }
      } else {
        // 如果 localCookie 字段不存在
        console.log("localCookie 字段不存在，执行其他操作...");
        // 在这里执行其他操作
      }
    }, 200); // 每隔一秒检查一次
  }
}
function goLoginFn() {
  console.log("------222222");
  // 获取当前点击跳转
  waitForElements(".goLogin").then((elements) => {
    console.log("------333");
    elements.forEach((button) => {
      button.addEventListener("click", () => {
        console.log("------3333");
        monitoring();
      });
    });
  });
}

goLoginFn();

// 获取当前点击跳转
waitForElements(".priData").then((elements) => {
  elements.forEach((button) => {
    button.addEventListener("click", () => {
      goLoginFn();
    });
  });
});
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message.message === "1") {
    location.reload();
  }
  if (message.message === "2") {
    console.log(message.message, "clickme 2");
    localStorage.removeItem(document.domain); //删除localStorage
    localStorage.setItem("hp", "2");
    page.monitorPopup();
  }
  if (message.action === "setLocalStorage") {
    // 设置本地存储值
    localStorage.setItem(message.key, message.value);
    sendResponse({ message: "Local storage value set successfully" });
    page.init();
  }
});
// 接收来自 background script 的消息
// chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
//   if (message.action === "setLocalStorage") {
//     // 设置本地存储值
//     localStorage.setItem(message.key, message.value);
//     sendResponse({ message: "Local storage value set successfully" });
//     page.init();
//   }
// });
